﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The regular-expression entity-identifier filter can be used to match facts based 
    /// upon regular patterns in the text of the entity identifier value. 
    /// </summary>
    public class RegExpIdentifierFilter : Filter
    {
        private string pattern;

        /// <returns> the @pattern attribute on the regular-expression entity-identifier filter. </returns>
        public string Pattern
        {
            get { return pattern; }
            set { pattern = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
         public RegExpIdentifierFilter(Linkbase.Resource resource)
             : base(resource)
        {
            string pattern = (string)resource.ResourceXElement.Attribute("pattern") ?? string.Empty;
            pattern = pattern.TrimEnd().TrimStart();
            pattern = Regex.Replace(pattern, @"\s+", " ");
            this.pattern = pattern;
        }


         public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
         {
             List<FactItem> itemListTemp = new List<FactItem>();

             foreach (FactItem item in itemsToFilter)
             {
                 string pattern = Pattern;
                 Match match = Regex.Match(item.ContextRef.Identifier, pattern);

                 if (Complement ? !(match.Length > 0) : match.Length > 0)
                 {
                     itemListTemp.Add(item);
                 }
             }

             return itemListTemp;
         }
    }
}
